package cn.lzh.controller;

import cn.lzh.entity.Book;
import cn.lzh.entity.BookType;
import cn.lzh.entity.Largefile;
import cn.lzh.service.BookService;
import cn.lzh.service.BooktypeService;
import cn.lzh.service.LargefileService;
import cn.lzh.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@CrossOrigin//允许跨域
@RestController
@RequestMapping("/api/adm/book")
public class BookController {
    @Autowired
    BookService bookService;
    @Autowired
    LargefileService largefileService;
    @Autowired
    BooktypeService booktypeService;

    //查询全部
     @RequestMapping("/findAll")
    public Map<String,Object> findAll(){
         List<Book> list = bookService.findAll();
       return RespJson.pack(200,"ok" ,list);
     }


      //查询一个
     @RequestMapping("/findByid/{bookid}")
    public Map<String,Object> findByid(@PathVariable Integer bookid){
         Book book = bookService.findById(bookid);
         return RespJson.pack(200,"ok",book);
     }


//添加
    @RequestMapping("/addBook")
    public Map<String,Object> addBook(@RequestParam("pic")MultipartFile file,Book book) throws IOException {
        Largefile largeFile = new Largefile();
        Map<String, Object> map = new HashMap<>();
        if (book.getId()==null||book.getId()==0){  //0表示添加
            if (file!=null &&file.getSize()>0){ // 判断是否有图片
                largeFile.setFilename(file.getOriginalFilename());//添加filename 名字
                byte[] buf = file.getBytes(); //  得到长度
                largeFile.setContent(buf);  //添加文件
                String s=UUID.randomUUID().toString();  //uuid 获取唯一的标识符
                largeFile.setId(s);
            }
            if (largeFile.getId()!=null){  //判断id 的值是否为空 如果为空不进行添加步骤
                book.setPicture(largeFile.getId()); //book的Picture是largefile id的值
                largefileService.addLargefile(largeFile);
            }
            bookService.add(book);
        }
        if (book.getId()>0){ // 》0表示修改
            if (file!=null && file.getSize()>0){
                Book book1 = bookService.findById(book.getId());
                System.out.println(book1);
                largefileService.delete(book1.getPicture());//删除旧图片

                largeFile.setFilename(file.getOriginalFilename());
                byte[] buf = file.getBytes();//  得到长度
                largeFile.setContent(buf);
                String s=UUID.randomUUID().toString(); //uuid 获取唯一的标识符
                largeFile.setId(s);
            }
            if (largeFile.getId()!=null){
                book.setPicture(largeFile.getId()); //book的Picture是largefile id的值
                largefileService.addLargefile(largeFile);
            }
            bookService.update(book);
        }
        book = bookService.findById(book.getId());
        System.out.println("添加的id="+book.getId());
        map.put("book", book);
        return RespJson.pack(200,"更新或添加成功...",map);
    }



    /*获得点赞前 5 的商品*/
    @ResponseBody
    @RequestMapping("/book/findRate5")
    public Map<String, Object> findRate5(){
        List<Book> lst = bookService.findRate5();
        return RespJson.pack(200, "获得点赞前 5 的商品",lst);
    }



    @RequestMapping("/findByPage/{start}/{num}")
    public Map<String, Object> findPagebook(@PathVariable("start") Integer start, @PathVariable("num") Integer num) {
        Map<String, Object> map = new HashMap();
        List<Book> lst = this.bookService.findPage(start - 1, num, 0);
        map.put("books", lst);
        map.put("total", 0);
       int count = this.bookService.getCount(0);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }


    @RequestMapping("/show/{id}")//显示图片
    public void show(@PathVariable String id, HttpServletResponse response) {
        if (id != null) {
            Largefile lg = this.largefileService.findById(id);
            byte[] buf = (byte[])(lg.getContent());

            try {
                response.setContentType("image/jpeg");
                response.getOutputStream().write(buf);
            } catch (Exception e) {
                System.err.println(e);
            }

        }
    }


    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
